<?php


namespace app\app\controller;

use think\Db;

class Tiankong extends Base
{

    public function __construct()
    {
        parent::__construct();
    }

    

    public function checkifcunzai()
    {
        $param = input();
        $iscunzai = db('m3u8_other_setting')->where(["vod_id" => $param['id']])->find();
        if ($iscunzai) {
            return $this->success('操作成功');
        } else {
            return $this->error(db()->getlastsql());
        }

    }

    public function index()
    {
        $data = input();

        if (!empty($data['title'])) {
            $list = db('vod')->field("vod_id, vod_name, vod_pic, vod_remarks, vod_actor")->where("vod_name like '%{$data['title']}%'")->order("vod_id asc")->select();
            // dump($list);
            $this->assign("list", $list);
            $this->assign("title", $data['title']);
        }

        return $this->fetch('app@tiankong/index');
    }

    public function vodindex()
    {
        $param = input();
        $param['page'] = intval($param['page']) < 1 ? 1 : $param['page'];
        $param['limit'] = intval($param['limit']) < 1 ? 20 : $param['limit'];
        $where = [];
        if (!empty($param['device_id'])) {
            $where['uh.device_id'] = $param['device_id'];
        }
        if (!empty($param['app_id'])) {
            $where['uh.app_id'] = $param['app_id'];
        }
        $order = 'uh.time_added desc';
        $page = $param['page'];
        $limit = $param['limit'];
        $start = 0;
        $limit_str = ($limit * ($page - 1) + $start) . "," . $limit;
        $total = \db('user_history')->alias('uh')->join('vod v', 'v.vod_id=uh.vod_id', 'LEFT')->where($where)->count();
        $list = \db('user_history')->alias('uh')->join('vod v', 'v.vod_id=uh.vod_id', 'LEFT')->where($where)->order($order)->limit($limit_str)->select();
        $applists = \db('banben')->column('app_id,appname as app_name');
        $this->assign('applists', $applists);
        $this->assign('list', $list);
        $this->assign('total', $total);
        $this->assign('page', $page);
        $this->assign('limit', $limit);

        $param['page'] = '{page}';
        $param['limit'] = '{limit}';
        $this->assign('param', $param);

        $this->assign('title', '影视访问记录');
        return $this->fetch('app@tiankong/vodindex');
    }

    public function search()
    {
        $data = input();
        $this->assign("vod_id", $data['vod_id']);
        $this->assign("vod_name", urldecode($data['vod_name']));
        $this->assign("keyword", urldecode($data['keyword']));
        return $this->fetch('app@tiankong/search');
    }

    public function info()
    {
        $data = input();

        if (Request()->isPost()) {
            $param = input('post.');
            if (empty(trim($param['url']))) {
                // $this->error('请输入链接');
            }

            $iscunzai = db('m3u8_cache_other')->where(["vod_id" => $param['vod_id']])->find();
            // dump($iscunzai);exit;
            if (empty($iscunzai)) {
                $res = db('m3u8_cache_other')->insert([
                    "vod_id" => $param['vod_id'],
                    "vod_name" => $param['vod_name'],
                    "key" => $param['key'],
                    "value" => str_replace(" ", "%20", $param['url']),
                    "time_added" => time(),
                    "from" => "tiantang"
                ]);
                $resdata = db('m3u8_other_setting')->insert([
                    "vod_id" => $param['vod_id'],
                    "vod_name" => $param['vod_name'],
                    "tiantang_id" => $param['tiantang_id'],
                    "tiantang_name" => $param['tiantang_name'],
                    "from" => "tiantang",
                    "is_lianzai" => $param['islianzai'],
                    "time_added" => time()
                ]);
                if ($res && $resdata) {
                    return $this->success('操作成功');
                } else {
                    return $this->error(db()->getlastsql());
                }
            } else {
                return $this->error('数据已存在');
            }
            exit;
        }

        // if(!empty($data['id'])) {
        //     $infodata = db('vod')->field("vod_id, vod_name, vod_pic")->where("vod_id = '{$data['id']}'")->find();
        //     // dump($list);
        //     $this->assign("infodata", $infodata);
        // }
        $this->assign("vod_id", $data['vod_id']);
        $this->assign("vod_name", urldecode($data['vod_name']));
        $this->assign("tiantang_name", urldecode($data['tiantang_name']));
        $this->assign("tiantang_id", $data['tiantang_id']);

        return $this->fetch('app@tiankong/info');
    }
    
    public function lianzaiupdate() {
        $data = input();
        $res = db('m3u8_other_setting')->where(["vod_id" => $data['vodId']])->find();
        $iscunzai = db('m3u8_other_setting')->where(["vod_id" => $data['vodId']])->update([
            'is_lianzai' => ($res['is_lianzai'] == 1) ? 0 : 1
            ]);
        return $this->success('操作成功');
    }

    public function list()
    {
        $data = input();

        if (!empty($data['vod_id'])) {
            $listdata = db('m3u8_cache_other')->where("vod_id = '{$data['vod_id']}'")->order("id desc")->select();
            $this->assign("listdata", $listdata);
            $this->assign("vod_id", $data['vod_id']);

            $datavo = db('m3u8_other_setting')->field("id, vod_id, vod_name, is_lianzai")->where("vod_id = '{$data['vod_id']}'")->order("id desc")->find();
            $this->assign("datavo", $datavo);
        } else {
            $listdata = db('m3u8_cache_other')->where("is_need_deal = '1'")->order("id desc")->select();
            $this->assign("listdata", $listdata);
        }

        $infodata = db('m3u8_other_setting')->field("id, vod_id, vod_name, is_lianzai")->order("id desc")->select();
        $this->assign("infodata", $infodata);

        //是否加入到推荐
        $find = \db('recommend_vod')->where('vod_id',$data['vod_id'])->count()?:0;
        $this->assign('isFindRecommend',$find?true:false);
        return $this->fetch('app@tiankong/list');
    }

    public function listdel()
    {
        $data = input();
        $resdata = db('m3u8_cache_other')->where("id='{$data['id']}'")->delete();
            if ($resdata) {
                return $this->success('操作成功');
            } else {
                return $this->error(db()->getlastsql());
            }
            exit;
    }

    public function listinfo()
    {
        $data = input();

        if (Request()->isPost()) {
            $param = input('post.');
            if (empty(trim($param['url']))) {
                $this->error('请输入链接');
            }

            $resdata = db('m3u8_cache_other')->where("id='{$param['id']}'")->update([
                "value" => str_replace(" ", "%20", $param['url']),
                "key" => $param['key'],
                "is_need_deal" => 0,
                "time_added" => time()
            ]);
            if ($resdata) {
                return $this->success('操作成功');
            } else {
                return $this->error(db()->getlastsql());
            }
            exit;
        }

        if (!empty($data['id'])) {
            $infodata = db('m3u8_cache_other')->where("id = '{$data['id']}'")->find();
            // dump($list);
            $this->assign("infodata", $infodata);
        }
        return $this->fetch('app@tiankong/listinfo');
    }

    public function detailcachetwonew()
    {
        $id = input('vod_id', 0, 'intval');
        if ($id < 1) {
            $this->error('数据有误！');
        }
        $time = time();
        $input = input();

        $data = cache('VOD_DETAIL_NEW_INFO_TIANKONG15' . $id);
        if (empty($data)) {
            $data = Db::name('Vod')->field('vod_id,vod_name,vod_pic,vod_play_from,vod_play_url,vod_blurb,vod_content,vod_time,vod_actor,vod_actor,is_cache,vod_area,vod_pic_thumb,vod_pic_slide,vod_remarks,vod_copyright')->where('vod_id', $id)->where('vod_status', 1)->find();
            if (empty($data)) {
                $data = [];
            } else {
                $data['vod_time'] = date('Y-m-d H:i', $data['vod_time']);
                $data['vod_pic'] = strpos($data['vod_pic'], 'http') === 0 ? $data['vod_pic'] : (request()->domain() . '/' . $data['vod_pic']);
                $data['vod_pic_thumb'] = $data['vod_pic_thumb'] ? (strpos(
                    $data['vod_pic_thumb'],
                    'http'
                ) === 0 ? $data['vod_pic_thumb'] : (request()->domain() . '/' . $data['vod_pic_thumb'])) : '';
                $v['vod_pic_slide'] = $data['vod_pic_slide'] ? (strpos(
                    $data['vod_pic_slide'],
                    'http'
                ) === 0 ? $data['vod_pic_slide'] : (request()->domain() . '/' . $data['vod_pic_slide'])) : '';

                $data['vod_content'] = strip_tags($data['vod_content']);
//                $data['vod_actor'] = explode(',', $data['vod_actor']);
                $data['ism3u8'] = 1;
                $data['fileurl'] = [];
                $sortOrder = 'asc';
                if (in_array($data['type_id_1'], [3]) || in_array($data['type_id'], [3])) {
                    $sortOrder = 'desc';
                }
                $ttCache = \db('m3u8_cache_other')->fieldRaw('sort as `index`, `value`  as url, `key` as name,1 as ism3u8 ')->where('from', 'tiantang')->where('vod_id', $data['vod_id'])->where('is_need_deal', 0)->order('sort', $sortOrder)->select();
                if (!empty($ttCache)) {
//                    foreach ($ttCache as $key => &$ttCachejuji) {
//                        $ttCachejuji['index'] = $key;
//                    }

                    $data['fileurl'][] = [
                        'sort' => 0,
                        "len" => count($ttCache),
                        'from' => [
                            'from' => '最大影院',
                            'sort' => 0,
                            'show' => '最大影院',
                            'id' => 'tiantang'
                        ],
                        'playlist' => $ttCache
                    ];
                }


                $bjCache = \db('m3u8_cache_bj')->fieldRaw('sort as `index`, CASE WHEN cache_value is not null THEN cache_value ELSE `value` END as url, `key` as name,1 as ism3u8 ')->where('vod_id', $data['vod_id'])->order('sort', $sortOrder)->select();
                if (!empty($bjCache)) {
//                    foreach ($bjCache as $key => &$bjCachejuji) {
//                        $bjCachejuji['index'] = $key;
//                    }

                    $data['fileurl'][] = [
                        'sort' => 1,
                        "len" => count($bjCache),
                        'from' => [
                            'from' => '最大影院',
                            'sort' => 1,
                            'show' => '最大影院',
                            'id' => 'localbj'
                        ],
                        'playlist' => $bjCache
                    ];
                }

                $localCache = \db('m3u8_cache')->fieldRaw('sort as `index`, CASE WHEN cache_value is not null THEN cache_value ELSE `value` END as url, `key` as name,1 as ism3u8 ')->where('vod_id', $data['vod_id'])->order('sort', $sortOrder)->select();
                if (!empty($localCache)) {
//                    foreach ($localCache as $key => &$juji) {
//                        $juji['index'] = $key;
//                    }

                    $data['fileurl'][] = [
                        'sort' => 2,
                        "len" => count($localCache),
                        'from' => [
                            'from' => '最大影院',
                            'sort' => 2,
                            'show' => '最大影院',
                            'id' => 'local'
                        ],
                        'playlist' => $localCache
                    ];
                }

                if (!empty($data['fileurl'])) {
                    // unset($data['vod_play_from']);
                    // unset($data['vod_play_server']);
                    // unset($data['vod_play_url']);
                    if (count($data['fileurl']) > 1) {
                        usort($data['fileurl'], function ($a, $b) {
                            if ($a['len'] < $b['len']) {
                                return 1;
                            } elseif ($a['len'] == $b['len']) {
                                if ($a['from']['sort'] > $b['from']['sort']) {
                                    return 1;
                                } else {
                                    return 0;
                                }
                            } else
                                return -1;

                        });
                    }
                    $data_fileurl[] = $data['fileurl'][0];
                    $data['fileurl'] = $data_fileurl;
                }

                //调用原数据最大信息
                $playNames = getPlayerNames();
                $playGroups = [];
                $playfroms = explode('$$$', $data['vod_play_from']);
                unset($data['vod_play_from']);
                $playNotes = explode('$$$', $data['vod_play_note']);
                unset($data['vod_play_note']);
                unset($data['vod_play_server']);
                $playUrls = explode('$$$', $data['vod_play_url']);
                unset($data['vod_play_url']);
                foreach ($playUrls as $key => $jujiurl) {
                    //解析url
                    $jujis = explode('#', $jujiurl);
                    $playList = [];
                    foreach ($jujis as $juji) {
                        list($name, $url) = explode('$', $juji);
                        $playList[] = [
                            'name' => $name,
                            'url' => $url,
                        ];
                    }
                    $playGroups[$key] = [
                        'playlist' => $playList,
                        'from' => [
                            'from' => $playNames[$playfroms[$key]]['from'],
                            'sort' => $playNames[$playfroms[$key]]['sort'],
                            'show' => $playNames[$playfroms[$key]]['show'],
                            'id' => $playNames[$playfroms[$key]]['id']
                        ],
                        'len' => count($playList)
                    ];
                }
                if (count($playGroups) > 1) {
                    //按序号排序
                    usort($playGroups, function ($a, $b) {
                        if ($a['len'] < $b['len']) {
                            return 1;
                        } elseif ($a['len'] == $b['len']) {
                            if ($a['from']['sort'] > $b['from']['sort']) {
                                return 1;
                            } else {
                                return 0;
                            }
                        } else
                            return -1;

                    });

                }
                $data_fileurl2[] = $playGroups[0];
                $data['fileurl2'] = $data_fileurl2;

                if (empty($data['fileurl'])) {
                    $data['fileurl'] = $data['fileurl2'];
                    $data['fileurl'][0]['playlist'][0]['from']['show'] = "最大影院";
                    $data['fileurl'][0]['from']['show'] = "最大影院";
                }

                //影视网站
                $data['fileurl3'] = [
                    /*[
                        "id" => "1",
                        "url" => "https://www.yzpsb.net/index.php?m=vod-search&wd=",
                        "from" => "侠客分享网",
                    ],
                    [
                        "id" => "2",
                        "url" => "http://www.xigua12.com/search.php?searchword=",
                        "from" => "西瓜影院",
                    ],
                    [
                        "id" => "3",
                        "url" => "https://www.oktvtt.com/search/wd-",
                        "from" => "ok电影天堂",
                    ],
                    [
                        "id" => "4",
                        "url" => "http://m.hrbsm.net/tv-search-wd-",
                        "from" => "哈片网",
                    ],
                    [
                        "id" => "5",
                        "url" => "http://www.yingshi163.com/vod-search.html?wd=",
                        "from" => "影视163",
                    ],*/
                ];
            }


            if ($data['image_down'] > 0) {
                $data['vod_pic'] = "http://7dfjeh.aojiasen.cn/cover/" . $data['vod_id'] . '.jpg';
            }
            $data['share_image'] = \db('config')->where('name', 'share_image')->value('value');
            $data['player_image'] = \db('config')->where('name', 'player_image')->value('value');
            cache('VOD_DETAIL_NEW_INFO_TIANKONG15' . $id, $data, 300);
        }

        if (!empty($input['app_id'])) {
            \db('user_history')->insert(
                [
                    'device_id' => $input['device_id'],
                    'device_name' => $input['device_name'],
                    'app_id' => $input['app_id'],
                    'app_name' => $input['app_name'],
                    'vod_id' => $input['vod_id'],
                    'system_type' => $input['system_type'],
                    'time_added' => $time,
                    'push_id' => $input['pageParam.pushId'] ?: 0
                ]
            );
            $inputArray = [
                'app_id' => $input['app_id'],
                'app_name' => $input['app_name'],
                'key_name' => $input['keyname'],
                'device_id' => $input['device_id'],
                'device_name' => $input['device_name'],
                'app_version' => $input['app_version'],
                'vod_id' => $input['vod_id'],
                'vod_name' => $data['vod_name'],
                'adtype' => '-2',
                'memo' => '获取详情',
                'ctime' => $time
            ];
            db('openadlog')->insertGetId($inputArray);
        }
        $this->success('获取成功', $data);
    }

    public function matchVodIndex()
    {
        $param = input();
        $param['page'] = intval($param['page']) < 1 ? 1 : $param['page'];
        $param['limit'] = intval($param['limit']) < 1 ? 100 : $param['limit'];
        $where = [];

        $order = 'v.vod_time desc';
        $list = \db('vod')->alias('v')
            ->where(['v.type_id|v.type_id_1'=>['in',[1,2,4]]])
            ->where('v.type_id','<>',37)
            ->whereTime('v.vod_time','today')
            ->join('m3u8_other_setting mos','mos.vod_id=v.vod_id','LEFT')
            ->where('mos.tiantang_id is null')
            ->field("v.*")
            ->where($where)->order($order)->select();
//        dump(\db()->getLastSql());
//        dump($list);
        $this->assign('list', $list);
//        $this->assign('total', $list->total());
//        $this->assign('page', $list->currentPage());
//        $this->assign('limit', $list->listRows());
//
//        $param['page'] = '{page}';
//        $param['limit'] = '{limit}';
//        $this->assign('param', $param);

        $this->assign('title', '影视更新匹配');
        return $this->fetch('app@tiankong/matchvodindex');
    }

    public function addTuijian(){
        $vodId = input('vodId',0,'intval');
        if($vodId<1){
            $this->error('数据错误！');
        }

        $find = \db('recommend_vod')->where('vod_id',$vodId)->find();

        if(empty($find)){
            \db('recommend_vod')->insertGetId([
                'sort_manual'=>1,
                'sort'=>999,
                'vod_id'=>$vodId,
                'recommend_id'=>22,
                'time_added'=>time()
            ]);
            $this->success('操作成功！');
        }else{
            $this->error('已经添加进去了');
        }
    }
}